<?php
namespace app\admin\controller;
use think\facade\Db;
use think\facade\View;
class Weihu extends Base
{
    /*
     * 开关
     */
	public function open()
	{
		$config = tpCache('open');
		View::assign('config',$config);//当前配置项
		return View::fetch();
	}
	
	/*
	 * 新增修改配置
	 */
	public function save()
	{
		$param = I('post.');
		$inc_type = $param['inc_type'];
		unset($param['inc_type']);
		tpCache($inc_type,$param);                

		$this->success("操作成功");
	}

	/*
	 * 钱包
	 */
	public function wallet(){
        //获取钱包
        $wallet = logic('Wallet')->getName();
        View::assign('wallet',$wallet);

	    if(IS_POST){
            $param = input('post.');
            $wallet_name = $param['wallet_name'];
            $wallet_key = $param['wallet_key'];

            //根据key值
            $new_wallet = [];$wallet_tx=[];$wallet_cz=[];
            //判断字段
            foreach($wallet_key as $key=>$val){
                if(!empty($val)){
                    $name='';
                    //名字为空
                    if(empty($wallet_name[$key])){
                        //继承之前的
                        if(isset($wallet[$val])){
//                            $name = $wallet[$val];
                        }
                    }else{
                        $name = $wallet_name[$key];
                    }
                    if($name!=''){
                        $new_wallet[$val] = $name;
                        $wallet_tx[$val] = $param['tx'][$key];
                        $wallet_cz[$val] = $param['cz'][$key];
                    }
                }
            }

            if(!$new_wallet){
                return json(['status'=>0,'msg'=>'钱包有误']);
            }
            //新增的入库
            $new = array_diff($new_wallet,$wallet);
            unset($new['money']);
            if($new){
                foreach($new as $key=>$val){
                    //判断是否存在
                    $check = logic('Dbbase')->checkField('wallet',$key);
                    if(!$check) {
                        //增加钱包字段
                        $rs = Db::execute("alter table sy_wallet add `" . $key . "` decimal(18,2) default 0 comment '" . $val . "'");
                        if ($rs === false) {
                            return json(['status'=>0,'msg'=>'更新钱包字段失败']);
                        }
                        //增加明细表
                        $rs = Db::execute("CREATE TABLE `sy_" . $key . "_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL DEFAULT '0',
  `money` decimal(18,2) NOT NULL DEFAULT '0.00',
  `yue` decimal(18,2) NOT NULL DEFAULT '0.00',
  `action` varchar(100) NOT NULL DEFAULT '',
  `desc` varchar(255) NOT NULL DEFAULT '',
  `w_time` int(11) NOT NULL DEFAULT '0',
  `type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8");
                        if ($rs === false) {
                            return json(['status'=>0,'msg'=>'增加钱包明细表失败']);
                        }
                    }
                }
            }

            //更新设置
            $data = [
                'name'=> $new_wallet,
                'tx'=> $wallet_tx,
                'cz'=> $wallet_cz,
            ];
            tpCache('wallet',$data);
            return json(['status'=>1,'msg'=>'设置成功']);
        }else{

            //获取提现
            $tx = logic('Wallet')->getTx();
            View::assign('tx',$tx);
            //获取在线充值
            $cz = logic('Wallet')->getCz();
            View::assign('cz',$cz);
            return View::fetch();
        }
    }

    /**
     * 清空演示数据
     *
     */
    public function chushiDb66del(){
        if(IS_POST){
            $data = input('post.');
            if(empty($data['title'])){
                return json(['status'=>0,'msg'=>'请输入随身携带的设备密钥']);
            }else{
                $my = date('YmdH').'sy888'.date('i');
                if($data['title']!=$my){
                    return json(['status'=>0,'msg'=>'密钥输入失败，请检查设备']);
                }
            }
            //获取所有表
            $result = Db::query('show tables');
            $tables = array();
            foreach($result as $key => $val){
                $tables[] = array_shift($val);
            }
            //基础表-不能清
            $base = array('sy_ad','sy_ad_position','sy_admin','sy_admin_role','sy_article','sy_article_cat','sy_choujiang_type','sy_config','sy_freight_config',
                'sy_freight_region','sy_freight_template','sy_friend_link','sy_goods_leixing','sy_payrule','sy_plugin','sy_region','sy_shipping','sy_sms_template',
                'sy_suppliers','sy_system_menu','sy_transfer_set','sy_user_level','sy_users','sy_wallet','sy_wx_user','sy_tuan_cate','sy_user_level1','sy_user_level2',
                'sy_user_level3','sy_designerpage','sy_designer_menu','sy_design_login','sy_wx_set','sy_wx_app_set','sy_transfer_set','sy_oss_set','sy_imgai_sysset','sy_app_set',
                'sy_admin_set_poster','sy_pay_way'
            );
            //产品
            $goods = array('sy_goods','sy_goods_attr','sy_goods_attribute','sy_goods_category','sy_goods_images','sy_goods_type','sy_spec','sy_spec_goods_price','sy_spec_image','sy_spec_item');

            $bl_table = $base;
            if(!isset($data['biao']['goods'])){
                $bl_table = array_merge($bl_table,$goods);
            }
            foreach($tables as $key => $val)
            {
                if(!in_array($val, $bl_table))
                {
                    Db::execute("truncate table ".$val);
                }
            }

            //删除其他管理员
            Db::execute('delete from sy_admin where admin_id>1');
//            Db::execute('delete from sy_admin_role where role_id>1');
            //会员相关
            Db::execute('delete from sy_users where user_id>1');
            Db::execute('alter table sy_users AUTO_INCREMENT=1');
            Db::execute('delete from sy_wallet where user_id>1');
            Db::execute('alter table sy_wallet AUTO_INCREMENT=1');
            Db::execute('delete from sy_suppliers where id>1');
            Db::execute('alter table sy_suppliers AUTO_INCREMENT=1');

            Db::execute('update sy_goods set sales_sum=0');
            Db::execute("update sy_users set tjnum=0,totalnum=0,shop_price=0,tjnum1=0,total_htlv=0,small_htlv=0,bank_huming='',erweima='',level=10,level1=1,level2=1,is_vip=1,head_pic='',reg_time=".time().",lj_xiaofei=0,zfb_erweima='',wx_erweima='',is_jxs=1,total_ayeji=0,month_ayeji=0,month_pv23=0,shouyi=0,total_pv1=0,gl_left='',team_yeji=0,gl_left_totalnum=0,gl_left_monthnum=0,gl_left_daynum=0,gl_right='',gl_right_totalnum=0,gl_right_monthnum=0,gl_right_daynum=0,up_month_pv23=0,dup_month_pv23=0,idcard='',self_ayeji=0,jw_time=".time().",jihuo_time=".time());
            //钱包
            $wallet = logic('Wallet')->getName();
            $str='';
            foreach($wallet as $key=>$val){
                $str.=','.$key.'=0';
            }
            $str=trim($str,",");
            Db::execute("update sy_wallet set ".$str);
            if(isset($data['goods'])) {
                delFile('../public/upload/goods'); // 清空测试图片
            }
            //清空钱包
            $wallet = logic('Wallet')->getName();
            $data = [];
            foreach($wallet as $key=>$name){
                $data[$key] = 0;
            }
            Db::name('wallet')->where('user_id',1)->save($data);
            //delete from sy_config where inc_type not in ('open','wallet','userdata','goodsprice','shop_info','basic','sms','smtp','express')
            //delete from sy_payrule where id>1; alter table sy_payrule AUTO_INCREMENT=1;
            //delete from sy_goods_leixing where id>1; alter table sy_goods_leixing AUTO_INCREMENT=1;
            //delete from sy_user_level where level_id>1;alter table sy_user_level AUTO_INCREMENT=1;
            $this->success('初始化成功');
        }else{
            return View::fetch('chushiDb66del');
        }
    }

    /**
     * 会员数据
     */
    public function userdata(){
        if(IS_POST){
            $data = input('post.');
            if(!isset($data['login_method'])){
                $data['login_method'] = [];
            }
            tpCache('userdata',$data);
            $this->success('设置成功');
        }else{
            //可设置会员信息
            $ary = config('userdata');
            $config = tpCache('userdata');
            View::assign('ary',$ary);
            View::assign('config',$config);
            return View::fetch();
        }
    }

    /**
     * 商品价格
     */
    public function goodsprice(){
        if(IS_POST){
            $post = input('post.');
            $config = tpCache('goodsprice');
            $data = [];
            foreach($post['field'] as $key=>$val){
                if($val!='' && $post['name'][$key]!='' && isset($post['leixing'][$key])){
                   $data[$val]=[
                       'field'=>$val,
                       'name'=>$post['name'][$key],
                       'leixing'=>$post['leixing'][$key]
                   ];
                }
                if(empty($post['leixing'][$key])){
                    Db::name('config')->where(['name'=>$key,'inc_type'=>'goodsprice'])->delete();
                }
            }
            if($data){
                //新增数据库
                foreach($data as $val){
                    logic('Dbbase')->addField('goods',$val['field']);//产品
                    logic('Dbbase')->addField('cart',$val['field']);//购物车
                    logic('Dbbase')->addField('spec_goods_price',$val['field']);//规格
                    logic('Dbbase')->addField('order','total_'.$val['field']);//订单
                    logic('Dbbase')->addField('order_goods',$val['field']);//订单产品
                }

                tpCache('goodsprice',$data);
                return json(['status'=>1,'msg'=>'设置成功']);
            }else{
                return json(['status'=>0,'msg'=>'如需添加，请在某一个行勾选和填写所有项']);
            }

        }else{
            //获取商品类型
            $leixing = logic('GoodsLogic')->getLeixing();
            $config = tpCache('goodsprice');
            View::assign('leixing',$leixing);
            View::assign('config',$config?:[]);
            return View::fetch();
        }
    }
}